﻿using B.S.Orders.Domain;
using B.S.Orders.ErrorCord;
using B.S.Orders.Write.Api.Application.Command.DispatchProductCommand;
using MediatR;
using SqlSugar;

namespace B.S.Orders.Write.Api.Application.CommandHander.DispatchProductCommandHandler
{
    public class DelDispatchProductCommandHandler : IRequestHandler<DelDispatchProductCommand, APIResult<object>>
    {
        private readonly ISqlSugarClient db;

        public DelDispatchProductCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<APIResult<object>> Handle(DelDispatchProductCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.success;
            result.Msg = "删除成功";
            var ids = request.ids.Split(',').Select(int.Parse).ToList();

            // 一次性查询所有要删除的派工记录
            var itemsToDelete = await db.Queryable<DispatchProduct>().Where(p => ids.Contains(p.DispatchProductId)).ToListAsync();

            foreach (var item in itemsToDelete)
            {
                await db.Deleteable(item).ExecuteCommandAsync();
            }

            // 一次性查询所有要删除的派工明细记录
            var iToDelete = await db.Queryable<DispatchDetails>().Where(p => ids.Contains(p.DispatchProductId)).ToListAsync();

            foreach (var item in iToDelete)
            {
                await db.Deleteable(item).ExecuteCommandAsync();
            }

            return result;
        }
    }
}
